'use strict';
 
angular.module('Report')
    .controller('PersonOutputController', ['$scope', '$http', '$q', '$stateParams', '$timeout', 'BaseModule', 'BaseEnum', 'BaseFunction','PersonOutputService','$filter',
        function($scope, $http, $q, $stateParams, $timeout, BaseModule, BaseEnum, BaseFunction,PersonOutputService,$filter) {
            $scope.dateStart = '';
            $scope.dateEnd = '';
            $scope.selectDateType = 0;//选中期间类型
            $scope.dateIsEnable = false;//选择日期是否可用
            $scope.dateType = {
                today: { Value: 0, Text: '今天' },
                yesterday: { Value: 1, Text: '昨天' },
                thisWeek: { Value: 2, Text: '本周' },
                thisMonth: { Value: 3, Text: '本月' },
                diyDate: { Value: 4, Text: '自定义' }
            };
 
            $scope.isShow = true;

            var startDay,endDay;//用于查询的其实结束天
           
            var year,month,day;//现在年月日
            var now = new Date();                    //当前日期     
            var nowDayOfWeek = now.getDay();         //今天本周的第几天
            if(nowDayOfWeek===0){
                nowDayOfWeek=7;
            }     
            var nowDay = now.getDate();              //当前日     
            var nowMonth = now.getMonth();           //当前月     
            var nowYear = now.getFullYear();             //当前年 
 
            BaseModule.initModule($scope, '_PersonOutput');
            $scope.Module._PersonOutput.LoadMode = BaseEnum.LoadMode.CacheAndPaging;
            $scope.Module._PersonOutput.PageSize = 15;
        
            var addData = [{
                user: "user1",
                works: [{
                     workName:"work1",
                     items:[{
                        itemName:"总数",
                        num:3
                     },{
                        itemName:"item1",
                        num:2
                     },{
                        itemName:"item2",
                        num:1
                     }]
                },{
                     workName:"work2",
                     items:[{
                        itemName:"总数",
                        num:2
                     },{
                        itemName:"item1",
                        num:1
                     },{
                        itemName:"item3",
                        num:1
                     }]
                }]
            },{
                user: "user2"
            },{
                user: "user3"
            }]
 
            // $scope.rowChange = function(){
            //     var fouscRecord = $scope.Module._PersonOutput.FocusedRecord;
            //     if (fouscRecord){
            //         for (var i = 0; i < $scope.Module._PersonOutput.Records.length; i++) {
            //             if($scope.Module._PersonOutput.Records[i].user===fouscRecord.user){
            //                  addBarChart($scope.Module._PersonOutput.Records[i]);
            //             }
            //         }
            //     }
            // };
            $scope.rowChange = function(){
                var fouscRecord = $scope.Module._PersonOutput.FocusedRecord;
                if (fouscRecord){
                    BaseFunction.loading(true); 
                
                    PersonOutputService.getDetailPersonOutput(startDay,endDay,$scope.Module.Department.FocusedRecord._id,fouscRecord._id).then(function (result) {
                        BaseFunction.loading(false); 
                        addBarChart(result);
                        
                    },function(error){
                        BaseFunction.loading(false);
                        
                        if(error){
                           BaseFunction.alert(error.message, error.title); 
                        }
                    });
                    
                }
            };
 
            //循环添加柱状图
            function addBarChart(works){
               document.getElementById('barchart').innerHTML = '';//清空barchart div下内容
               
               for (var i = 0; i < works.length; i++) {
                   addDiv(i);//添加柱状图div
               }
               for (var i = 0; i < works.length; i++) {
                   drawBarChart(works[i],i);//绘制柱状图
               }
            }
            
             function addDiv(i){
                var newNode=document.createElement("div");   
                newNode.id="barchart"+(i+1);
                newNode.style.width="100%"; 
                newNode.style.height="200px"; 
                
                document.getElementById("barchart").appendChild(newNode);   
            }
            //
            function drawBarChart(work,i) {
                var myChart = echarts.init(document.getElementById('barchart'+(i+1)));
                var itemNames = ["总数"];
                var nums = [work.WorkSum];
                for (var i = 0; i < work.ItemMasters.length; i++) {
                    itemNames.push(work.ItemMasters[i].itemName);
                    nums.push(work.ItemMasters[i].num);
                }
                
                var option = {
                    title: {
                        text: work.workName,
                        padding: 20
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['数量']
                    },
                    xAxis: [{
                        type: 'category',
                        data: itemNames,
                    }],
                    yAxis: [{
                        type: 'value',
                       
                    }],
                    series: [{
                        name: '数量',
                        type: 'bar',
                        data: nums
                    }]
                };
                myChart.setOption(option);
                window.onresize = myChart.resize;
            }
 
 
            $scope.selectType = function() {
                if ($scope.selectDateType === 4) {
                    $scope.dateIsEnable = 'true';
                }else{
                    $scope.dateIsEnable = 'false';
                }
            };
 
            //格式化日期：yyyy-MM-dd     
            function formatDate(date) {      
                var myyear = date.getFullYear();     
                var mymonth = date.getMonth()+1;     
                var myweekday = date.getDate();      
                     
                if(mymonth < 10){     
                    mymonth = "0" + mymonth;     
                }      
                if(myweekday < 10){     
                    myweekday = "0" + myweekday;     
                }     
                return (myyear+"-"+mymonth + "-" + myweekday);      
            }
            //获得某月的天数     
            function getMonthDays(myMonth){     
                var monthStartDate = new Date(nowYear, myMonth, 1);      
                var monthEndDate = new Date(nowYear, myMonth + 1, 1);      
                var   days   =   (monthEndDate   -   monthStartDate)/(1000   *   60   *   60   *   24);      
                return   days;      
            }  
            //获取当天日期
            function getToday(){
                return formatDate(now);
            }
            //获取昨天日期
            function getYesterday(){
                var yesterdayDate = new Date(nowYear, nowMonth, nowDay - 1);      
                return formatDate(yesterdayDate); 
            }
            //获得本周的开始日期     
            function getWeekStartDate() {      
                var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);      
                return formatDate(weekStartDate);     
            }      
                
            //获得本周的结束日期     
            function getWeekEndDate() {      
                var weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek));      
                return formatDate(weekEndDate);     
            }      
                
            //获得本月的开始日期     
            function getMonthStartDate(){     
                var monthStartDate = new Date(nowYear, nowMonth, 1);      
                return formatDate(monthStartDate);     
            }     
                
            //获得本月的结束日期     
            function getMonthEndDate(){     
                var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));      
                return formatDate(monthEndDate);     
            }
 
            console.log("今天"+getToday()+'\n'+
                        "昨天"+getYesterday()+'\n'+
                        "本周开始"+getWeekStartDate()+'\n'+
                        "本周结束"+getWeekEndDate()+'\n'+
                        "本月开始"+getMonthStartDate()+'\n'+
                        "本月结束"+getMonthEndDate());       
 
 
            $scope.search = function() {
                
                if($scope.selectDateType===0){//今天
                    startDay = getToday();
                    endDay = getToday();
                }
                if ($scope.selectDateType===1) {//昨天
                    startDay = getYesterday();
                    endDay = getYesterday();
                }
                if ($scope.selectDateType===2) {//本周
                    startDay = getWeekStartDate();
                    endDay = getWeekEndDate();
                }
                if ($scope.selectDateType===3) {//本月
                    startDay = getMonthStartDate();
                    endDay = getMonthEndDate();
                }
                if ($scope.selectDateType===4){//自定义
                    startDay = formatDate(new Date($scope.dateStart));
                    endDay = formatDate(new Date($scope.dateEnd));
                }
                BaseFunction.loading(true); 
                
                PersonOutputService.getPersonOutputByDate(startDay,endDay,$scope.Module.Department.FocusedRecord._id).then(function (result) {
                    BaseFunction.loading(false); 
                    
                    if(result.length>0){
                        var resultData = $filter('orderBy')(result, ['user'], false);
                        $scope.Module._PersonOutput.Records = resultData; 
                        
                    }else{
                        $scope.Module._PersonOutput.Records = result;
                        document.getElementById('barchart').innerHTML = '';//清空barchart div下内容
                        BaseFunction.alert("未找到对应数据"); 
                    }

                    $scope.Module._PersonOutput.emitOnLoadEvent();//发送载入完成时间，刷新DataGrid
                    
                },function(error){
                    BaseFunction.loading(false);
                    $scope.Module._PersonOutput.Records = []; 
                    $scope.Module._PersonOutput.emitOnLoadEvent();
                    
                    document.getElementById('barchart').innerHTML = '';//清空barchart div下内容
                    if(error){
                       BaseFunction.alert(error.message, error.title); 
                    }
                });
            }
        }
])